from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, QueryDict
from utils.auth import login_required, conn_k8s_api
from utils.dateformat import dt_format
from kubernetes import client
import time
from utils.node_data import node_info, node_resource


# Create your views here.

@login_required
def nodes(request):
    return render(request, "k8smanager/nodes.html")


@login_required
def node_tabledata(request):
    auth_type = request.session.get("auth_type", False)
    conn_k8s_api(request, auth_type=auth_type)
    core_api = client.CoreV1Api()
    if request.method == "GET":
        node_list = []
        try:
            for node in core_api.list_node_with_http_info()[0].items:
                name = node.metadata.name
                labels = node.metadata.labels
                status = node.status.conditions[-1].type
                ipaddr = node.status.addresses[0].address
                scheduler = ("是" if node.spec.unschedulable is None else "否")
                cpu = node.status.capacity['cpu']
                memory = node.status.capacity['memory']
                kebelet_version = node.status.node_info.kubelet_version
                cri_version = node.status.node_info.container_runtime_version
                os_version = node.status.node_info.os_image
                create_time = node.metadata.creation_timestamp
                node = {"name": name, "labels": labels, "status": status,
                        "scheduler": scheduler, "cpu": cpu, "memory": memory,
                        "kebelet_version": kebelet_version, "cri_version": cri_version,
                        "create_time": create_time, "os_version": os_version, "ipaddr": ipaddr}
                search_key = request.GET.get("key", None)
                if search_key:
                    if search_key in name:  # in 则为模糊查询
                        node_list.append(node)
                else:
                    node_list.append(node)
            count = len(node_list)
            page = int(request.GET.get("page"))
            limit = int(request.GET.get("limit"))
            start = (page - 1) * limit
            end = page * limit
            node_list = node_list[start:end]
            code = 0
            msg = "node节点信息获取成功！"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "无权限！"
            else:
                msg = "查询失败！"
            code = 1
        return JsonResponse({"code": code, "data": node_list, "msg": msg, "count": count})
    elif request.method == "DELETE":
        pass


# node详情页信息 包括节点资源和节点信息
@login_required
def node_details(request):
    auth_type = request.session.get("auth_type", False)
    conn_k8s_api(request, auth_type=auth_type)
    core_api = client.CoreV1Api()

    node_name = request.GET.get("node_name")

    node_r = node_resource(core_api, node_name)
    node_i = node_info(core_api, node_name)

    return render(request, "k8smanager/node_details.html",
                  {"node_name": node_name, "node_resources": node_r, "node_info": node_i})

# node详情页的pod列表
@login_required
def node_details_pod_list(request):
    auth_type = request.session.get("auth_type", False)
    conn_k8s_api(request, auth_type=auth_type)
    core_api = client.CoreV1Api()

    node_name = request.GET.get("node_name")

    pod_list = []
    try:
        for pod in core_api.list_pod_for_all_namespaces().items:
            name = pod.spec.node_name
            pod_name = pod.metadata.name
            namespace = pod.metadata.namespace
            status = ("运行中" if pod.status.conditions[-1].status else "异常")
            host_network = pod.spec.host_network
            pod_ip = ("主机网络" if host_network else pod.status.pod_ip)
            create_time = dt_format(pod.metadata.creation_timestamp)

            if name == node_name:
                if len(pod.spec.containers) == 1:
                    cpu_requests = "0"
                    cpu_limits = "0"
                    memory_requests = "0"
                    memory_limits = "0"
                    for c in pod.spec.containers:
                        # c_name = c.name
                        # c_image= c.image
                        # cpu_requests = "0"
                        # cpu_limits = "0"
                        # memory_requests = "0"
                        # memory_limits = "0"
                        if c.resources.requests is not None:
                            if "cpu" in c.resources.requests:
                                cpu_requests = c.resources.requests["cpu"]
                            if "memory" in c.resources.requests:
                                memory_requests = c.resources.requests["memory"]
                        if c.resources.limits is not None:
                            if "cpu" in c.resources.limits:
                                cpu_limits = c.resources.limits["cpu"]
                            if "memory" in c.resources.limits:
                                memory_limits = c.resources.limits["memory"]
                else:
                    cpu_request = "0"
                    cpu_limit = "0"
                    memory_request = "0"
                    memory_limit = "0"
                    cpu_requests = ""
                    cpu_limits = ""
                    memory_requests = ""
                    memory_limits = ""
                    for c in pod.spec.containers:
                        c_name = c.name
                        # c_image= c.image
                        if c.resources.requests is not None:
                            if "cpu" in c.resources.requests:
                                cpu_request = c.resources.requests["cpu"]
                            if "memory" in c.resources.requests:
                                memory_request = c.resources.requests["memory"]
                        if c.resources.limits is not None:
                            if "cpu" in c.resources.limits:
                                cpu_limit = c.resources.limits["cpu"]
                            if "memory" in c.resources.limits:
                                memory_limit = c.resources.limits["memory"]

                        cpu_requests += "%s=%s<br>" % (c_name, cpu_request)
                        cpu_limits += "%s=%s<br>" % (c_name, cpu_limit)
                        memory_requests += "%s=%s<br>" % (c_name, memory_request)
                        memory_limits += "%s=%s<br>" % (c_name, memory_limit)

                pod = {"pod_name": pod_name, "namespace": namespace, "status": status, "pod_ip": pod_ip,
                       "cpu_requests": cpu_requests, "cpu_limits": cpu_limits, "memory_requests": memory_requests,
                       "memory_limits": memory_limits, "create_time": create_time}
                pod_list.append(pod)

        count = len(pod_list)
        page = int(request.GET.get("page"))
        limit = int(request.GET.get("limit"))
        start = (page - 1) * limit
        end = page * limit
        pod_list = pod_list[start:end]
        code = 0
        msg = "pod数据获取成功！"
    except Exception as e:
        status = getattr(e, "status")
        if status == 403:
            msg = "无权限！"
        else:
            msg = "查询失败！"
        code = 1
    return JsonResponse({"code": code, "data": pod_list, "msg": msg, "count": count})


@login_required
def namespaces(request):
    return render(request, "k8smanager/namespace.html")


@login_required
def ns_tabledata(request):
    auth_type = request.session.get("auth_type", False)
    conn_k8s_api(request, auth_type=auth_type)
    core_api = client.CoreV1Api()
    if request.method == "GET":
        ns_list = []
        try:
            for ns in core_api.list_namespace().items:  # items返回一个对象，类LIST（[{命名空间属性},{命名空间属性}] ），每个元素是一个类字典（命名空间属性），操作类字典
                name = ns.metadata.name
                labels = ns.metadata.labels
                create_time = ns.metadata.creation_timestamp
                create_time = dt_format(create_time)
                namespace = {"name": name, "labels": labels, "create_time": create_time}
                search_key = request.GET.get("key", None)
                if search_key:
                    if search_key in name:  # in 则为模糊查询
                        ns_list.append(namespace)
                else:
                    ns_list.append(namespace)
            count = len(ns_list)
            page = int(request.GET.get("page"))
            limit = int(request.GET.get("limit"))
            start = (page - 1) * limit
            end = page * limit
            ns_list = ns_list[start:end]
            code = 0
            msg = "namespace获取成功！"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "无权限！"
            else:
                msg = "查询失败！"
            code = 1
        return JsonResponse({"code": code, "data": ns_list, "msg": msg, "count": count})
    elif request.method == "DELETE":
        del_data = QueryDict(request.body)
        try:
            name = del_data.get('name')
            core_api.delete_namespace(name=name)
            while True:
                name_list = []
                for ns in core_api.list_namespace().items:  # items返回一个对象，类LIST（[{命名空间属性},{命名空间属性}] ），每个元素是一个类字典（命名空间属性），操作类字典
                    name_list.append(ns.metadata.name)
                if name not in name_list:
                    break
                else:
                    time.sleep(1)  # 调用k8s接口删除，需要等待k8s响应
            code = 0
            msg = "删除数据成功！"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "无权限！"
            else:
                msg = "删除失败！"
            code = 1
        data = {'code': code, 'msg': msg}
        return JsonResponse(data)
    elif request.method == "POST":
        namespace = request.POST.get("name")
        for ns in core_api.list_namespace().items:
            if namespace == ns.metadata.name:
                return JsonResponse({'code': -1, 'msg': namespace + "已存在！"})
        try:
            body = client.V1Namespace(
                api_version="v1",
                kind="Namespace",
                metadata=client.V1ObjectMeta(
                    name=namespace
                )
            )
            core_api.create_namespace(body=body)
            code = 0
            msg = "创建成功"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "无权限！"
            else:
                msg = "创建失败！"
            code = 1
        data = {"code": code, "msg": msg}
        return JsonResponse(data)


@login_required
def pv(request):
    return render(request, "k8smanager/pv.html")


@login_required
def pv_tabledata(request):
    auth_type = request.session.get("auth_type", False)
    conn_k8s_api(request, auth_type=auth_type)
    core_api = client.CoreV1Api()
    if request.method == "GET":
        pv_list = []
        try:
            for pv in core_api.list_persistent_volume().items:
                name = pv.metadata.name
                capacity = pv.spec.capacity["storage"]
                access_modes = pv.spec.access_modes
                reclaim_policy = pv.spec.persistent_volume_reclaim_policy
                status = pv.status.phase
                if pv.spec.claim_ref is not None:
                    pvc_ns = pv.spec.claim_ref.namespace
                    pvc_name = pv.spec.claim_ref.name
                    pvc = "%s / %s" % (pvc_ns, pvc_name)
                else:
                    pvc = "未绑定"
                storage_class = pv.spec.storage_class_name
                create_time = pv.metadata.creation_timestamp
                create_time = dt_format(create_time)
                pv = {"name": name, "capacity": capacity, "access_modes": access_modes,
                      "reclaim_policy": reclaim_policy, "status": status, "pvc": pvc,
                      "storage_class": storage_class, "create_time": create_time}
                search_key = request.GET.get("key", None)
                if search_key:
                    if search_key in name:  # in 则为模糊查询
                        pv_list.append(pv)
                else:
                    pv_list.append(pv)
            count = len(pv_list)
            page = int(request.GET.get("page"))
            limit = int(request.GET.get("limit"))
            start = (page - 1) * limit
            end = page * limit
            pv_list = pv_list[start:end]
            code = 0
            msg = "pv获取成功！"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "无权限！"
            else:
                msg = "查询失败！"
            code = 1
        return JsonResponse({"code": code, "data": pv_list, "msg": msg, "count": count})
    elif request.method == "DELETE":
        del_data = QueryDict(request.body)
        try:
            name = del_data.get('name')
            core_api.delete_persistent_volume(name=name)
            while True:
                name_list = []
                for pv in core_api.list_persistent_volume().items:  # items返回一个对象，类LIST（[{命名空间属性},{命名空间属性}] ），每个元素是一个类字典（命名空间属性），操作类字典
                    name_list.append(pv.metadata.name)
                if name not in name_list:
                    break
                else:
                    time.sleep(1)  # 调用k8s接口删除，需要等待k8s响应
            code = 0
            msg = "删除数据成功！"
        except Exception as e:
            status = getattr(e, "status")
            if status == 403:
                msg = "无权限！"
            else:
                msg = "删除失败！"
            code = 1
        data = {'code': code, 'msg': msg}
        return JsonResponse(data)
